<?php
namespace App\Repositories\Admin;

use App\Models\Admin\SearchModel;
use App\Repositories\BaseRepository;

class SearchRepository extends BaseRepository
{
    protected $repository;

    public function __construct()
    {
        $this->repository = new SearchModel();
    }

    public function getIndex($word)
    {
        return $this->repository
            ->where('content','like','%'.$word.'%')
            ->orderBy('id','desc')
            ->get();
    }

    public function getApiIndex($word,$type)
    {
        $where = [];
        if($type){
            $where['type']=$type;
        }
        return $this->repository
            ->where($where)
            ->where('content','like','%'.$word.'%')
            ->orderBy('id','desc')
            ->skip(0)
            ->take(5)
            ->get();
    }

    public function setAdd($data)
    {
        $data['created_at'] = time();
        return $this->repository->insertGetId($data);
    }

    public function setModifyByType($type,$fromId,$data)
    {
        $model = $this->repository
            ->where('type',$type)
            ->where('from',$fromId)
            ->first();
        if (!$model) { return $this->setAdd($data); }
        return $this->repository
            ->where('type',$type)
            ->where('from',$fromId)
            ->update($data);
    }

    public function getShowOne($id)
    {
        return $this->repository->where('id',$id)->first();
    }

    public function getTypes()
    {
        return $this->repository->getTypes();
    }

    public function getTypeName($type)
    {
        $types = $this->repository->getTypes();
        return array_key_exists($type,$types) ?
            $types[$type] : '';
    }
}